CC = $(CROSS)g++
AR = $(CROSS)ar
SR = $(CROSS)g++ -shared
LD = $(CROSS)ld

CURDIR   ?= $(shell pwd)

TARGET   := $(BUILDIN)

SUBDIRS   = libavi
#TIRDLIRS  = 
TIRDLIRS  = termcap readline

SRC_FILES := $(wildcard *.cpp)
OBJ_FILES := $(SRC_FILES:.cpp=.o)

SUB_FILES := $(addsuffix /$(BUILDIN),$(SUBDIRS))
EXT_FILES := 

subdir     := $(addprefix build_,$(SUBDIRS) )
subdir     += $(addprefix build_,$(TIRDLIRS))
clean_dirs := $(addprefix clean_,$(SUBDIRS) )

CFLAGS     := $(CC_FLAGS)
CFLAGS     += $(PWD)/out/third/include/ -ltermcap

export PWD
export CROSS
export CFLAGS
export CC_CROSS

# default rule
default: all

# non-phony targets
$(TARGET): $(OBJ_FILES)
	@echo "LD  $(TARGET)"
	$(LD) $(LD_FLAGS) -r -o $@ $(OBJ_FILES) $(SUB_FILES) $(EXT_FILES)

$(OBJ_FILES): %.o:%.cpp
	@echo "$(CC_FLAGS)"
	$(CC) $(CFLAGS) -c -o $@ $<

$(SUBDIRS):
	make -C $@

$(subdir):
	@echo "CC  $@"
	$(MAKE) -C $(patsubst build_%,%,$@)

$(clean_dirs):
	$(MAKE) -C $(patsubst clean_%,%,$@) clean

# phony rules
.PHONY: all 
all: $(subdir) $(TARGET)

.PHONY: clean
clean: $(clean_dirs)
	rm -f *.o
